package com.codejoys.monitor.service.impl;

import com.codejoys.monitor.domain.*;
import com.codejoys.monitor.mapper.ConfigMapper;
import com.codejoys.monitor.mapper.SysConfigMapper;
import com.codejoys.monitor.mapper.VoltageModeConfigMapper;
import com.codejoys.monitor.service.ConfigService;
import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class ConfigServiceImpl implements ConfigService {
    @Autowired
    ConfigMapper mapper;

    @Autowired
    VoltageModeConfigMapper vmMapper;

    @Autowired
    SysConfigMapper sysConfigMapper;

    @Override
    public List<Config> findAll(String house) {
        ConfigExample e = new ConfigExample();
        e.createCriteria().andHouseEqualTo(house);

        return mapper.selectByExample(e);
    }

    @Override
    public void deleteById(Integer id) {
        mapper.deleteByPrimaryKey(id);
    }

    @Override
    public void update(Config config) {
        mapper.updateByPrimaryKeySelective(config);
    }

    @Override
    public void insert(Config config) {
        mapper.insert(config);
    }

    @Override
    public void insertVoltageMode(VoltageModeConfig config) {
        vmMapper.insert(config);
    }

    @Override
    public void updateVoltageMode(VoltageModeConfig config) {
        vmMapper.updateByPrimaryKeySelective(config);
    }

    @Override
    public void deleteVoltageModeById(Integer id) {
        vmMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<VoltageModeConfig> findAllVoltageModeConfig() {
        return vmMapper.selectByExample(null);
    }

    @Override
    public void insertSysConfig(SysConfig config) {
        sysConfigMapper.insert(config);
    }

    @Override
    public void updateSysConfig(SysConfig config) {
        sysConfigMapper.updateByPrimaryKeySelective(config);
    }

    @Override
    public void deleteSysConfigById(Integer id) {
        sysConfigMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<SysConfig> findAllSysConfig() {
        return sysConfigMapper.selectByExample(null);
    }

    @Override
    public void insertSysConfigs(List<SysConfig> configs) {
        if (configs == null || configs.size() == 0) return;

        SysConfigExample e = new SysConfigExample();
        e.createCriteria().andNameIn(configs.stream().map(c -> c.getName()).collect(Collectors.toList()));

        // 删除已有配置
        sysConfigMapper.deleteByExample(e);

        // 插入新数据
        configs.forEach(c -> {
            sysConfigMapper.insertSelective(c);
        });
    }
}
